/**
 * 邮件服务
 * 提供邮件发送功能
 */

const nodemailer = require('nodemailer');
const { logInfo, logError } = require('../logger');

// 创建邮件传输器
const createTransporter = () => {
  // 对于163邮箱，使用明确的SMTP配置
  if (process.env.EMAIL_SERVICE === '163') {
    return nodemailer.createTransport({
      host: 'smtp.163.com',
      port: 465,
      secure: true,
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
      },
      // 添加调试信息
      debug: process.env.NODE_ENV === 'development',
      logger: process.env.NODE_ENV === 'development'
    });
  }
  
  // 其他邮箱服务使用默认配置
  return nodemailer.createTransport({
    service: process.env.EMAIL_SERVICE || 'gmail',
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASS
    },
    // 添加调试信息
    debug: process.env.NODE_ENV === 'development',
    logger: process.env.NODE_ENV === 'development'
  });
};

/**
 * 发送邮件
 * @param {string} to - 收件人邮箱
 * @param {string} subject - 邮件主题
 * @param {string} text - 邮件文本内容
 * @param {string} html - 邮件HTML内容
 * @returns {Promise<Object>} 邮件发送结果
 */
const sendEmail = async (to, subject, text, html) => {
  try {
    // 创建邮件传输器
    const transporter = createTransporter();
    
    // 定义邮件选项
    const mailOptions = {
      from: process.env.EMAIL_FROM || process.env.EMAIL_USER,
      to,
      subject,
      text,
      html
    };
    
    // 发送邮件
    const result = await transporter.sendMail(mailOptions);
    logInfo('邮件发送成功', { to, subject });
    return { success: true, result };
  } catch (error) {
    logError('邮件发送失败', { 
      error: error.message, 
      code: error.code,
      command: error.command,
      response: error.response,
      to, 
      subject 
    });
    return { success: false, error: error.message };
  }
};

/**
 * 发送验证码邮件
 * @param {string} to - 收件人邮箱
 * @param {string} code - 验证码
 * @returns {Promise<Object>} 邮件发送结果
 */
const sendVerificationCode = async (to, code) => {
  const subject = '【心灵洞察指南】邮箱验证码';
  const text = `您的验证码是：${code}，有效期为5分钟。如非本人操作，请忽略此邮件。`;
  const html = `
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
      <h2 style="color: #333;">邮箱验证码</h2>
      <p>您好！</p>
      <p>您正在注册心灵洞察指南账户，验证码为：</p>
      <div style="background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0;">
        ${code}
      </div>
      <p>该验证码有效期为5分钟，请尽快使用。</p>
      <p>如非本人操作，请忽略此邮件。</p>
      <hr style="margin: 30px 0; border: none; border-top: 1px solid #eee;">
      <p style="color: #999; font-size: 12px;">此邮件由系统自动发送，请勿回复。</p>
    </div>
  `;
  
  return await sendEmail(to, subject, text, html);
};

module.exports = {
  sendEmail,
  sendVerificationCode
};